﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using log4net;
using AutoFacUtils;
using CashFlow.Web.Service;
using CashFlow.Web.Common;
using System.Text;

namespace CashFlow.Web.Filters
{
    public class RootUserFilterAttribute : ActionFilterAttribute
    {
        private static ILog _logger = LogManager.GetLogger(typeof(RootUserFilterAttribute));
        private IUserService GetUserService() { return AutoFacHelper.Get<IUserService>(); }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var userService = GetUserService();
            if (userService.IsRootUser())
            {
                base.OnActionExecuting(filterContext);
            }
            else
            {
                _logger.Error(filterContext.HttpContext.Request.Url);
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.HttpContext.Response.ClearContent();
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new ContentResult
                {
                    Content = "403",
                    ContentEncoding = Encoding.UTF8,
                    ContentType = "text/html"
                };
            }
        }
    }
}